package com.logservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sml.response.LogRedisVO;
import com.sml.response.LogView;
import com.logservice.service.LogService;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Author linlx
 * @Date 2021/9/7 10:32
 * @Description
 **/
@Service
public class LogServiceImpl implements LogService {

  @Resource
  private StringRedisTemplate stringRedisTemplate;

  @Override
  public List<LogView> getLog(String feignId) {
    Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(feignId);
    List<LogView> logViewList = new ArrayList<>(map.size());
    map.forEach((k, v) -> {
      LogView logView = new LogView();
      logView.setServiceName(String.valueOf(k));
      LogRedisVO logRedisVO = JSONObject.parseObject(String.valueOf(v), LogRedisVO.class);
      logView.setLogRedisVO(logRedisVO);
      logViewList.add(logView);
    });
    return logViewList;
  }

  @Override
  public List<List<LogView>> getLogAll() {
    Set<String> keys = stringRedisTemplate.keys("*");
    assert keys != null;
    List<List<LogView>> result = new ArrayList<>(keys.size());
    keys.forEach(key -> {
      List<LogView> logViewList = new ArrayList<>();
      Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(key);
      map.forEach((k, v) -> {
        LogView logView = new LogView();
        logView.setServiceName(String.valueOf(k));
        LogRedisVO logRedisVO = JSONObject.parseObject(String.valueOf(v), LogRedisVO.class);
        logView.setLogRedisVO(logRedisVO);
        logViewList.add(logView);
      });
      result.add(logViewList);
    });
    return result;
  }
}
